#!/usr/bin/env python

import argparse
import os
from os.path import abspath, join, dirname, splitext
import sys
import time

sys.path.insert(0, abspath(join(dirname(__file__), "common")))
import shelltest, test_framework, unit, utils

tests = None

# helper function for loading tests from full_test/*.test
def generate_test(tree):
    def gen(test_command, name):
        i = 1
        new_name = name
        while tree.has_test(new_name):
            i = i + 1
            new_name = name + '-' + str(i)
        tree[new_name] = shelltest.ShellCommandTest(test_command)
    return gen

# load the tests from full_test/*.test
def load_tests():
    dirpath = join(dirname(__file__), "full_test")
    for filename in os.listdir(dirpath):
        base_name, ext = splitext(filename)
        if ext == '.test':
            tree = test_framework.TestTree();
            full_path = os.path.join(dirpath, filename)
            execfile(full_path, {"__builtins__": __builtins__, "generate_test": generate_test(tree)})
            tests.add(base_name, tree)

# Test groups
groups = {}

# Load the test groups from full_test/*.group
def load_groups():
    dirpath = join(dirname(__file__), "full_test")
    for filename in os.listdir(dirpath):
        base_name, ext = splitext(filename)
        if ext == '.group':
            full_path = os.path.join(dirpath, filename)
            groups[base_name] = test_framework.group_from_file(full_path)

# Take the requirements for the tests, and build a configuration
def configure(reqs, args):
    src_root = utils.project_root_dir
    if args.build_dir:
        build_dir = args.build_dir
    else:
        build_dir = utils.latest_build_dir()
    return dict(SRC_ROOT=src_root, BUILD_DIR=build_dir)

if __name__ == '__main__':
    # Initialise the list of tests with the dumy tests and the unit tests
    tests = test_framework.TestTree({
        'unit': unit.AllUnitTests()
    })

    argparser = argparse.ArgumentParser(parents=[test_framework.argparser])
    argparser.add_argument('-b', '--build-dir', default=None,
                           help='The rethinkdb build directory (Default: the latest one)')

    args = argparser.parse_args(sys.argv[1:])
    load_tests()
    load_groups()
    ret = test_framework.run(tests, groups, lambda reqs: configure(reqs, args), args)
    if ret is not None:
        sys.exit(1)
